package leetcode_bin_tree_test;

import bin_tree_order.Main.TreeNode;

import java.util.*;

/**
 *  二叉树的层平均值
 */
public class AverageLevel {
    public List<Double> averageOfLevels(TreeNode root) {
        // 层序遍历
        // 使用双端队列
        List<Double> list = new ArrayList<>();
//        if (root == null) {
//            return list;
//        }
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            int sum = 0; // 记录本层的和
            for (int i = 0; i < size; i++) {
                TreeNode node = deque.poll();
                sum += node.val;
                if (node.left != null) {
                    deque.offer(node.left);
                }
                if (node.right != null) {
                    deque.offer(node.right);
                }
            }
            list.add((1.00000 * sum) / size);
        }
        return list;
    }
}

